package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
import com.lawyer.config.BaseConfigUrlBean;
import com.lawyer.entity.Lawyer;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.model.TokenInfo;
import com.lawyer.repository.LawyerRepository;

@RestController
@Api(tags = "律师端登陆注册")
@RequestMapping(value = "/lawyerFactory")
public class LawyerLoginController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private BaseConfigUrlBean baseConfigUrlBean;

	@Autowired
	private LawyerRepository lawyerRepository;

	protected final String USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "律师端授权登陆", notes = "律师端授权登陆")
	public HttpEntity<?> login(String accessToken, String openId, String unionid,String cid) {
		Message msg = new Message();
		Map<String, Object> map = new HashMap<String, Object>();
		String userInfoUrl = String.format(USER_INFO, accessToken, openId);
		RestTemplate restTemplate = new RestTemplate();
		MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		headers.put("Content-Type", Lists.newArrayList(MediaType.APPLICATION_JSON_VALUE));
		ResponseEntity<String> userEntity = restTemplate.exchange(userInfoUrl, HttpMethod.GET, null, String.class);
        String blackJson = new String(userEntity.getBody().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
		ReadContext ctx = JsonPath.parse(blackJson);
		try {
			String nickname = ctx.read("$.nickname");
			String headimgurl = ctx.read("$.headimgurl");

			Lawyer findLawyer = lawyerRepository.findOne(unionid);
			if (findLawyer == null) {
				Lawyer saveLawyer = new Lawyer();
				saveLawyer.setCid(cid);
				saveLawyer.setHeaderIco(headimgurl);
				saveLawyer.setId(unionid);
				saveLawyer.setNickName(nickname);
				saveLawyer.setEnabled(true);
				saveLawyer.setUsername(unionid);
				saveLawyer.setComprehensiveScore(0D);
				saveLawyer.setIsFree(true);
				saveLawyer.setOnLine("1");
				saveLawyer.setBalance(0D);
				saveLawyer.setLabel("");
				saveLawyer.setCertification(0);
				saveLawyer.setIntroduceMyself("");
				saveLawyer.setPassword("WYAyPRZAKOqJnYnD0A9vC6hMs2yArey0zu2X+65C9Y7QfoWURZh7F1k==");
				findLawyer = lawyerRepository.save(saveLawyer);
				saveLawyer.setId(null);
				// 保存到oatuh2
				new RestTemplate().exchange(baseConfigUrlBean.getRegister(), HttpMethod.POST, new HttpEntity<>(saveLawyer,headers), Message.class);
			}else{
				//更新cid
				if(StringUtils.isNotEmpty(cid)){
					findLawyer.setCid(cid);
				}
				findLawyer.setOnLine("1");
				findLawyer = lawyerRepository.save(findLawyer);
			}

			ResponseEntity<TokenInfo> entity = restTemplate.exchange(baseConfigUrlBean.getLogin(), HttpMethod.POST, new HttpEntity<>(findLawyer,headers), TokenInfo.class);
			TokenInfo info = entity.getBody();
			findLawyer.setPassword(null);
			map.put("tokenInfo", info);
			map.put("userInfo", findLawyer);
			msg.setData(map);
		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);

		}
		return new ResponseEntity<>(msg, HttpStatus.OK);

	}

	// @RequestMapping(value = "/register", method = RequestMethod.POST)
	// @ApiOperation(httpMethod = "POST", value = "律师注册", notes =
	// "注册只需要传账号(username)密码(password)")
	// public HttpEntity<?> register(@RequestBody Lawyer lawyer) {
	// Message msg = new Message();
	// User user = new User();
	// Lawyer findLawyer =
	// lawyerRepository.findByUsername(lawyer.getUsername());
	// if (findLawyer == null) {
	// lawyerRepository.save(lawyer);
	//
	// user.setEnabled(true);
	// user.setUsername(lawyer.getUsername());
	// user.setPassword(lawyer.getPassword());
	// ResponseEntity<Message> entity = new
	// RestTemplate().exchange(baseConfigUrlBean.getRegister(), HttpMethod.POST,
	// new HttpEntity<>(user), Message.class);
	// msg.setData(entity.getBody());
	// return new ResponseEntity<>(msg, HttpStatus.OK);
	// } else {
	// msg.setCode(MessageConstant.FAILED_CODE);
	// msg.setMessage("账号已存在");
	// return new ResponseEntity<>(msg, HttpStatus.OK);
	// }
	//
	// }

	@RequestMapping(value = "/check", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "判断律师账号是否已注册", notes = "输入13位手机号码")
	public HttpEntity<?> check(String phone) {
		Message msg = new Message();
		Lawyer findLawyer = lawyerRepository.findByUsername(phone);
		if (findLawyer == null) {
			msg.setCode(MessageConstant.SUCCESS_CODE);
			msg.setMessage("账号不存在");
		} else {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("账号已存在");
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);

	}

}
